require 'active_record'
require 'yaml'

dbconfig = YAML::load(File.open('config/database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)

class Posts< ActiveRecord::Base
  set_table_name "wp_posts"
end

class Comments< ActiveRecord::Base
  set_table_name "wp_comments"
end

def process_post_data(parsed_post_data)
  begin
    post = Posts.new

    post.post_author = 1
    post.post_date = Time.parse(parsed_post_data.postDate)
    post.post_date_gmt = Time.parse(parsed_post_data.postDate)
    post.post_content = parsed_post_data.content
    post.post_title = parsed_post_data.title
    post.post_category = 0
    post.post_excerpt = parsed_post_data.excerpt
    post.post_status = "publish"
    post.comment_status = "open"
    post.ping_status = ""
    post.post_password = ""
    post.post_name = ""
    post.to_ping = ""
    post.pinged = ""
    post.post_modified = Time.parse(parsed_post_data.postDate)
    post.post_modified_gmt = Time.parse(parsed_post_data.postDate)
    post.post_content_filtered = ""
    post.post_parent = 0
    post.guid = "donno"
    post.menu_order = 0
    post.post_type = "post"
    post.post_mime_type = ""
    post.comment_count = parsed_post_data.commentsCount    
    post.save
    return post.ID
  rescue
    print "Error saving posts data :", $!, "\n"
    return 0
  end
end

def process_comment_data(parsedCommentData,id)
  i = parsedCommentData.author.size-1
  begin
    while i>=0
      comment = Comments.new
      comment.comment_post_ID = id
      comment.comment_author = parsedCommentData.author[i]
      comment.comment_author_email = parsedCommentData.email[i]
      comment.comment_author_url = parsedCommentData.website[i]
      comment.comment_author_IP = parsedCommentData.ipAddress[i]
      comment.comment_date = parsedCommentData.postDateSql[i]
      comment.comment_date_gmt = parsedCommentData.postDateSql[i]
      comment.comment_content = parsedCommentData.content[i]
      comment.comment_karma = 0
      comment.comment_approved = parsedCommentData.state[i]
      comment.comment_agent = ""
      comment.comment_type = ""
      comment.comment_parent = 0
      comment.user_id = 0
      comment.save
      i = i-1
    end
  rescue
    print "Error saving comments data", $!, "\n"
  end
end
